﻿/*************************************************************************
 *  Copyright © 2023-2030 Administrator. All rights reserved.
 *------------------------------------------------------------------------
 *  公司：DefaultCompany
 *  项目：ScriptHeadComments
 *  文件：PackageInitializer.cs
 *  作者：Administrator
 *  日期：2024/11/20 22:10:41
 *  功能：Nothing
*************************************************************************/

using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace ScriptHeadComments.Editor
{
    [InitializeOnLoad]
    public class PackageInitializer
    {
        static PackageInitializer()
        {
            EditorApplication.delayCall += OnEditorLoad;
        }

        private static void OnEditorLoad()
        {
            CreateBuildInfoResources();
        }

        private static void CreateBuildInfoResources()
        {
            string assetFilePath = Path.Combine(BasePath, "Resources", "ScriptHeadComments.asset");
            // 创建临时资源
            string tempAssetPath = Path.Combine("Assets", "ScriptHeadComments.asset");

            if (!File.Exists(assetFilePath))
            {
                ScriptHeadComments.CreateBuildInfoAsset(tempAssetPath);

                try
                {
                    // 确保目标路径的目录存在
                    string targetDirectory = Path.GetDirectoryName(assetFilePath);
                    if (!Directory.Exists(targetDirectory))
                    {
                        Directory.CreateDirectory(targetDirectory);
                    }

                    // 将资源从 Assets 拷贝到包路径
                    File.Move(tempAssetPath, assetFilePath);

                    Debug.Log($"No ScriptHeadComments.asset file found. Creating default at {assetFilePath}");

                    // 刷新资源数据库，确保资源被正确加载
                    AssetDatabase.Refresh();
                }
                catch (System.Exception ex)
                {
                    Debug.LogError($"Creating ScriptHeadComments.asset failed: {ex.Message}");
                }
            }
        }


        /// <summary>
        /// 从此处拷贝工具目录
        /// </summary>
        static string BasePath
        {
            get
            {
                var assembly = Assembly.GetExecutingAssembly();

                var pInfo = UnityEditor.PackageManager.PackageInfo.FindForAssembly(assembly);

                if (pInfo == null)
                    return null;

                var path = Path.GetFullPath(pInfo.assetPath);

                path = path.Replace('\\', '/');

                return path;
            }
        }
    }
}

